package com.code;

/**
 * 获取整数反序 超过int最大长度返回0
 * Created by lucky on 2018/9/26.
 */
public class Code4 {
    public static void main(String[] args) {
        int reverse = reversez(153423646);
        System.out.println(reverse);
    }

    public static int reversez(int x) {
        int rev = 0;
        while (x != 0) {
            int pop = x % 10;
            x /= 10;
            if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
            if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
            rev = rev * 10 + pop;
        }
        return rev;
    }

    public static int reverse(int x) {
        boolean flag = false;
        if(x < 0){
            flag = true;
            x = Math.abs(x);
        }
        Integer n = new Integer(x);
        int length = String.valueOf(n).length();
        Integer result = 0;
        int q = 0;
        for (int i = 0 ; i < length ; i ++){
            q++;
            Integer z = getNum(n,i,q);
            if(i == 0 && z == 0){
            }else{
                result += z * pow(length - i -1);
            }
        }
        if(flag){
            result = result * -1;
        }
        return result;
    }

    public static int getNum(int x , int i , int length){
        if(i==0){
            x = x % pow(i + 1);
        }else{
            x = x % pow(length) / pow(length - 1);
        }
        return x;
    }

    public static int pow(int m){
        int z = 1;
        for (int i = 0 ; i < m ; i++){
            z = z * 10;
        }
        return z;
    }
}
